﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;

namespace Nexterday.Linq.Autocompiler
{
    public class SimpleCompiledQueryCache : ICompiledQueryCache
    {
        static object _cacheLock = new object();
        static Dictionary<string, Delegate> _queryCache = new Dictionary<string, Delegate>();

        public static SimpleCompiledQueryCache Instance
        {
            get
            {
                return Nested.instance;
            }
        }

        class Nested
        {
            // Explicit static constructor to tell C# compiler
            // not to mark type as beforefieldinit
            static Nested()
            {
            }

            internal static readonly SimpleCompiledQueryCache instance = new SimpleCompiledQueryCache();
        }
        
        public SimpleCompiledQueryCache()
        {
        }


        
        #region ICompiledQueryCache Members

        public Delegate GetOrAdd<TResult>(string cacheKey, Func<string,Delegate> valueFactory)
        {
            Delegate query;
            if (!_queryCache.TryGetValue(cacheKey, out query))
            {
                query = valueFactory.Invoke(cacheKey);
                _queryCache[cacheKey] = query;
            }
            return query;
        }

        #endregion
    }
}
